require 'socket'
require 'thread'
require 'apiserverparser'
require 'fcntl'

class APIServerListener
  def initialize(unrealdb)
    @db = unrealdb
    @server_socket = TCPServer::new("0.0.0.0", LISTENER_PORT)
    @conns = []
    @thread_conns = []
    @loop_thread = nil
  end

  def listen
    @loop_thread = Thread.new do
      while true
        curr_thread = Thread.start(@server_socket.accept) do |s|
          begin
            s.fcntl(Fcntl::F_SETFL, Fcntl::O_NONBLOCK)
            @thread_conns << curr_thread
            conn = APIServerParser.new(@db, self, s)
            @conns << conn
            conn.run
          rescue Exception => e
            puts "Excecao na thread de uma conexao SERVERLISTENER: " + e.class.to_s + " : " + e.message
          end
        end
      end
    end
  end

  def conn_closed(conn)
    @conns.each{ |conn_ite| conn.close if conn_ite == conn }
    @conns.delete(conn)
  end

  def stop_server
    @loop_thread.kill if @loop_thread != nil
    @thread_conns.each{ |thread| thread.kill }
    @conns.each{ |conn| conn.close }
    @server_socket.close
  end
end